/**
 * @description Api request methods
 */

import Instance from './instance'
import Url from './url'

export default {
  get(url, data, rmEnd = false) {
    if (url) {
      let xhrInfo = transformUrl(url, data, rmEnd)

      return Instance({
        url: xhrInfo.url,
        method: 'get',
        params: xhrInfo.data
      })
    }
  },
  post(url, data, rmEnd) {
    if (url) {
      let xhrInfo = transformUrl(url, data, rmEnd)

      return Instance({
        url: xhrInfo.url,
        method: 'post',
        data: xhrInfo.data
      })
    }
  },
  put(url, data, rmEnd) {
    if (url) {
      let xhrInfo = transformUrl(url, data, rmEnd)

      return Instance({
        url: xhrInfo.url,
        method: 'put',
        data: xhrInfo.data
      })
    }
  },
  delete(url, data, rmEnd) {
    if (url) {
      let xhrInfo = transformUrl(url, data, rmEnd)

      return Instance({
        url: xhrInfo.url,
        method: 'delete',
        params: xhrInfo.data
      })
    }
  }
}

/**
 * @description Convert the url and data before the request
 * @param {string} origin_url Request origin URL
 * @param {Object} data Request parameters
 * @param {boolean} rmEnd optional,whether remove the request path tail '/'
 */
function transformUrl(origin_url, data, rmEnd) {
  let url = origin_url
  // Map the URL, otherwise it will be dominated by the original URL
  Url[origin_url] && (url = Url[origin_url])
  let reg = /:[\w_\-.]+/g
  let copiedUrl = url
  let copiedData = data !== undefined ? JSON.parse(JSON.stringify(data)) : data

  let matched = copiedUrl.match(reg)
  /**
   * Determines whether the target string ends with the specified string
   * @param {string} endStr Request end string
   */
  String.prototype.endWith = function(endStr) {
    let d = this.length - endStr.length

    return d >= 0 && this.lastIndexOf(endStr) === d
  }
  // Handle specified parameters
  matched &&
    matched.length &&
    matched.forEach(item => {
      let key = item.replace(/:/, '')
      let value = ''
      copiedData &&
        copiedData[key] !== undefined &&
        ((value = copiedData[key]), delete copiedData[key])

      copiedUrl = copiedUrl.replace(
        item + (copiedUrl.endWith(item) ? '' : '/'),
        value + (copiedUrl.endWith(item) ? '' : '/')
      )
    })

  // Remove redundant '/'
  copiedUrl = copiedUrl.replace(/\/\//g, '/')
  // Remove redundant '/',optional
  rmEnd &&
    copiedUrl.match(/.+\/$/) &&
    (copiedUrl = copiedUrl.substr(0, copiedUrl.length - 1))
  return {
    url: copiedUrl,
    data: copiedData
  }
}
